package com.platform.file.controller;

import cn.hutool.core.date.StopWatch;
import com.platform.common.core.constant.ServiceNameConstants;
import com.platform.common.core.exception.ServiceException;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.core.utils.file.FileUtils;
import com.platform.common.core.web.domain.AjaxResult;
import com.platform.common.security.utils.AESUtil_SC;
import com.platform.file.constant.SysFileConstants;
import com.platform.file.model.SysFile;
import com.platform.file.service.IDicFileLogService;
import com.platform.file.service.ISysFileService;
import com.platform.file.utils.FileUploadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/fileManage")
public class FileManageController {

    private static final Logger log = LoggerFactory.getLogger(FileManageController.class);
    @Value("${minio.filePrefix}")
    public String filePrefix;
    @Value("${minio.bucketName}")
    public String bucketName;
    @Resource
    private ISysFileService sysFileService;
    @Resource
    private IDicFileLogService fileLogService;

    /**
     * 完整路径请求
     */
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        String cataloguePrefix = SysFileConstants.PUBLIC;
        String serviceName = ServiceNameConstants.FILE_SERVICE;
        String url = "";
        String returnPath = filePrefix + '/' + bucketName + '/';
        String fileUrlSecret = null;
        try {
            // 上传并返回访问地址
            url = sysFileService.upload(file, serviceName, cataloguePrefix);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(returnPath + url);
            fileUrlSecret = AESUtil_SC.encryptNoBase64(bucketName + "/" + url, SysFileConstants.FILESECRET);
            return AjaxResult.success("文件上传成功！", sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return AjaxResult.error(e.getMessage());
        } finally {
            fileLogService.saveUploadLogNew(serviceName, file, url, bucketName, fileUrlSecret, cataloguePrefix, SysFileConstants.FILETAG_OTHER);
            stopWatch.stop();
            log.info("上传文件名的路径为{},上传耗时{}秒", url, stopWatch.getTotalTimeSeconds());
        }
    }


    /**
     * 完整路径请求
     */
    @PostMapping("/uploadNew")
    public AjaxResult uploadNew(MultipartFile file, String type, String fileTag) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        String cataloguePrefix = SysFileConstants.BUCKET_MAP.get(type);
        if (StringUtils.isEmpty(cataloguePrefix)) {
            //默认公共文件
            cataloguePrefix = SysFileConstants.PUBLIC;
        }
        /**文件标签，默认其他*/
        if (StringUtils.isEmpty(fileTag)) {
            fileTag = SysFileConstants.FILETAG_OTHER;
        }
        String serviceName = ServiceNameConstants.FILE_SERVICE;
        String url = "";
        String returnPath = filePrefix + '/';
        String fileUrlSecret = "";
        try {
            // 上传并返回访问地址
            url = sysFileService.upload(file, serviceName, cataloguePrefix);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            fileUrlSecret = AESUtil_SC.encryptNoBase64(bucketName + "/" + url, SysFileConstants.FILESECRET);
            sysFile.setUrl(fileUrlSecret);
            return AjaxResult.success("文件上传成功！", sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return AjaxResult.error(e.getMessage());
        } finally {
            fileLogService.saveUploadLogNew(serviceName, file, url, bucketName, fileUrlSecret, cataloguePrefix, fileTag);
            stopWatch.stop();
            log.info("上传文件名的路径为{},上传耗时{}秒", url, stopWatch.getTotalTimeSeconds());
        }
    }

    /**
     * 上传文件
     *
     * @param
     * @param
     * @return
     */
    @PostMapping("/uploadFileBatch")
    public AjaxResult uploadFile(@RequestParam("files") MultipartFile[] files) {
        if (files == null || files.length == 0) {
            return AjaxResult.error("上传文件不能为空");
        }
        String cataloguePrefix = SysFileConstants.PUBLIC;
        String serviceName = ServiceNameConstants.FILE_SERVICE;
        List<String> filePathList = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            String filePath = "";
            double reSize = 0;
            try {
                MultipartFile file = files[i];
                String fileName = file.getOriginalFilename();
                //判断文件大小是否超过20MB
                reSize = file.getSize();
                if ((reSize / 1024 / 1024) > SysFileConstants.FILE_MAX_VALUE) {
                    return AjaxResult.error("文件大小不能超过20MB，请重新上传");
                }
                filePath = cataloguePrefix + "/" + serviceName + "/" + System.currentTimeMillis() + "_" + fileName;
                String uploadFilePath = sysFileService.upload(file, serviceName, cataloguePrefix);
                filePathList.add(uploadFilePath);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("上传文件失败", e);
                return AjaxResult.error(e.getMessage());
            } finally {
                fileLogService.saveUploadLog(serviceName, filePath, reSize);
            }
        }
        return AjaxResult.success("文件上传成功！", filePathList);
    }

    /**
     * 上传文件
     *
     * @param
     * @param
     * @return
     */
    @PostMapping("/uploadFileBatchNew")
    public AjaxResult uploadFileNew(@RequestParam("files") MultipartFile[] files, String type, String fileTag) {
        if (files == null || files.length == 0) {
            return AjaxResult.error("上传文件不能为空");
        }
        String cataloguePrefix = SysFileConstants.BUCKET_MAP.get(type);
        if (StringUtils.isEmpty(cataloguePrefix)) {
            //默认公共文件
            cataloguePrefix = SysFileConstants.PUBLIC;
        }
        /**文件标签，默认其他*/
        if (StringUtils.isEmpty(fileTag)) {
            fileTag = SysFileConstants.FILETAG_OTHER;
        }
        String serviceName = ServiceNameConstants.FILE_SERVICE;
        List<String> filePathList = new ArrayList<>();
        String returnPath = filePrefix + '/';
        for (int i = 0; i < files.length; i++) {
            String filePath = "";
            double reSize = 0;
            String fileUrlSecret = "";
            try {
                MultipartFile file = files[i];
                String fileName = file.getOriginalFilename();
                //判断文件大小是否超过20MB
                reSize = file.getSize();
                if ((reSize / 1024 / 1024) > SysFileConstants.FILE_MAX_VALUE) {
                    return AjaxResult.error("文件大小不能超过20MB，请重新上传");
                }
                filePath = cataloguePrefix + "/" + serviceName + "/" + System.currentTimeMillis() + "_" + fileName;
                String uploadFilePath = sysFileService.upload(file, serviceName, cataloguePrefix);
                uploadFilePath = bucketName + "/" + uploadFilePath;
                fileUrlSecret = AESUtil_SC.encryptNoBase64(uploadFilePath, SysFileConstants.FILESECRET);
                filePathList.add(fileUrlSecret);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("上传文件失败", e);
                return AjaxResult.error(e.getMessage());
            } finally {
                fileLogService.saveUploadLogNew(serviceName, filePath, reSize, bucketName, fileUrlSecret, cataloguePrefix, fileTag);
            }
        }
        return AjaxResult.success("文件上传成功！", filePathList);
    }
}
